/* -*- Mode: java; indent-tabs-mode:nil; c-basic-offset: 2 -*-
 * ex: set sw=2 expandtab:
 * $Id: JErrorDialog.java,v 1.4 2003/07/30 11:47:14 kowey Exp $
 *
 * This software is released under a BSD-style license.
 * Please see the LICENSE file in this distribution.
 */

package be.donovan.gui.helper.components;

import java.awt.Component;
import java.awt.Dimension;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Displays an error message in a modal dialog, with an optional stack trace.
 * This is basically a customised call to the JOptionPane classes
 * 
 * @version $Revision: 1.4 $<br>
 *          $Date: 2003/07/30 11:47:14 $<br>
 * @author Eric Kow (kow at loria point fr)
 */
public class JErrorDialog extends JOptionPane {
	/**
	 * Show an error dialog for simple strings
	 */
	public static void showError(String message) {
		JOptionPane.showMessageDialog(null, message, "Oops!",
				JOptionPane.ERROR_MESSAGE);
	}

	/**
	 * Show an error dialog for strings plus something useful about an exception
	 */
	public static void showError(String message, Throwable e){
		
		showError(null,message,e);
	}
	
	public static void showError(Component top, String message, Throwable e) {
		e.printStackTrace();
		Object[] apologies = new Object[2];
		JTextArea jStackTrace = new JTextArea();
		StringWriter sw = new StringWriter();
		e.printStackTrace(new PrintWriter(sw));
		jStackTrace.setText(sw.toString());
		JScrollPane jStackTraceScroller = new JScrollPane(jStackTrace);
		setSize(jStackTraceScroller, 780, 400);
		jStackTrace.setEditable(false);
		jStackTrace.setLineWrap(true);
		apologies[0] = message + "\n\n";
		apologies[1] = jStackTraceScroller;

		JOptionPane.showMessageDialog(top, apologies,
				"Oops! Exception generated!", JOptionPane.ERROR_MESSAGE);
//		int x = JOptionPane.showConfirmDialog(null,
//				"Do you want to sent error message to the developers.",
//				"Send mail", JOptionPane.YES_NO_OPTION,
//				JOptionPane.QUESTION_MESSAGE);
//		;
//		if (x == JOptionPane.YES_OPTION) {
//			sendMail(e);
//		}
	}

	public static void sendMail(Throwable e) {
		try {
			StringWriter buffer = new StringWriter();
			buffer.append("-------\n");
			buffer.append("Add additional comment here!!!!!\n");
			buffer.append("-------\n");
			buffer.append('\n');
			buffer.append('\n');
			buffer.append('\n');
			buffer.append("Error:\n");
			e.printStackTrace(new PrintWriter(buffer));
			buffer.append('\n');
			buffer.append("Actions recorded:\n");
			for (String action : AbstractController.getActionRecorder()) {
				buffer.append(action);
				buffer.append('\n');
			}
			buffer.flush();
			Process process = Runtime.getRuntime().exec(
					new String[] {
							"rundll32",
							"url.dll,FileProtocolHandler",
							"mailto:+CCCIS/C/Appl/ProdCtl;&subject=Error in ATDL3&body="
									+ buffer.toString() }, null);// ","attachment;filename="+strFileName
			new JErrorDialog.MonitorInputStreamThread(process.getErrorStream()).start();
			new JErrorDialog.MonitorInputStreamThread(process.getInputStream()).start();
			
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}
	static class MonitorInputStreamThread extends Thread {

        private Reader reader;
        private Writer writer;

        public MonitorInputStreamThread(InputStream in) {

            reader = new InputStreamReader(new BufferedInputStream(in));
            writer = new OutputStreamWriter(System.out);
            setDaemon(true);
        }

        public void run() {

            try {
                int c;
                while ((c = reader.read()) != -1) {

                    writer.write(c);
                    writer.flush();
                }
            }
            catch (IOException ioe) {
                ioe.printStackTrace(System.out);
            }
            System.out.println("MonitorInputStreamThread exiting...");
        }
    }

	public static void setSize(Component component, int w, int h) {
		Dimension dimension = new Dimension(w, h);
		component.setMinimumSize(dimension);
		component.setMaximumSize(dimension);
		component.setSize(dimension);
		component.setPreferredSize(dimension);
	}

	// ---------------------------------------------------------------
	// class members
	// ---------------------------------------------------------------

	static Log _logger = LogFactory.getLog(JErrorDialog.class);
	final static int STACK_TRACE_WIDTH = 700;

	// ---------------------------------------------------------------
	// eyeball test
	// ---------------------------------------------------------------
//	public static void main(String args[]) {
//		final String eyeTag = "[JErrorDialog eyeball test] ";
//		try {
//			// do something which should generate an exception
//			fakeFn(0);
//		} catch (Exception e) {
//			JErrorDialog.showError("blah blah blah! curse like a sailor!", e);
//		}
//	}
//
//	// all this to generate an error
//	private static void fakeFn(int count) throws Exception {
//		if (count < 7)
//			fakeFn(count + 1);
//		else {
//			new JTextArea().getText(-42, 42);
//		}
//	}

} // end JErrorDialog

